import pathToRegexp from 'path-to-regexp';
const axios = window.axios;

// Add a request interceptor
axios.interceptors.request.use(
  config => {
    const url = config.url;
    if (url && url.indexOf(':')) {
      const toPath = pathToRegexp.compile(url);
      config.url = toPath(config.params);
    }
    if (!axios.defaults.headers['x-csrf-token']) {
      setCsrfToken();
    }
    // Do something before request is sent
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  },
);

// Add a response interceptor
axios.interceptors.response.use(
  response => {
    // Do something with response data
    return response;
  },
  error => {
    // token失效时处理
    window.log.error(error.msg);
    // Do something with response error
    return Promise.reject(error);
  },
);

const setCsrfToken = () => {
  function getCookie(name: string, cookies: string) {
    if (cookies) {
      const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
      const arr = cookies.match(reg);
      if (arr) {
        return unescape(arr[2]);
      }
    }
    return null;
  }
  const token = getCookie('csrfToken', document.cookie);

  window.log.warn(token);
  if (token) {
    axios.defaults.headers['x-csrf-token'] = token;
  }
};
